import React from 'react';
import { AutoComplete, Card, Image, Upload, Avatar } from 'antd';
import { Form, Input, Button, Checkbox, Select, message, Row, Col } from 'antd';
import { UploadOutlined } from '@ant-design/icons';


import axios from 'axios';
import { Url } from '../url';
const { Option } = Select;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};


const formatName = (name) => {
    if (name != undefined) {

        return name.split(" ").map(each => each.slice(0, 1).toUpperCase() + each.slice(1)).join(" ");
    } else {
        return "";
    }
}

export class Profile extends React.Component {
    onFinish = (values) => {
        values["id"] = this.obj["id"]
        //post the information to backend
        axios.post('http://localhost:8080/api/user/update', values)
            .then((response) => {
                if (response.data.success === false) {
                    message.error(response.data.errorMessage);
                } else {
                    message.success('save succeed');
                }
            })
            .catch((error) => {
                message.error("Network Error");
                console.log(error);
            });
    };

    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    }

    obj = {}
    //等到渲染完成后加载此函数
    componentDidMount = () => {

        if (this.props.match.params.id === "my") {
            //如果此user没有登录，会先跳转到登录界面
            if (localStorage.getItem("user") == null) {
                message.info("Please login first")
                setTimeout(() => {
                    window.location.href = "/#/login";
                }, 50);
            } else {
                //如果用户存在，将其转换为对象
                this.obj = JSON.parse(localStorage.getItem("user"))
                let userprofile = []
                //将对象转换成以下格式的数组[{"name":"userID","value":"test1"},{name:"password","value":"1"}]
                for (var i in this.obj) {
                    let profile = {}
                    profile["name"] = i
                    profile["value"] = this.obj[i]
                    userprofile.push(profile)
                }
                //用state保存变量的当前状态
                this.setState({
                    fieldList: userprofile
                })

            }
        } else {
            axios.get(Url.viewUser + this.props.match.params.id)
                .then(response => {
                    this.obj = { ...response.data }
                    let userprofile = []
                    //将对象转换成以下格式的数组[{"name":"userID","value":"test1"},{name:"password","value":"1"}]
                    for (var i in this.obj) {
                        let profile = {}
                        profile["name"] = i
                        profile["value"] = this.obj[i]
                        userprofile.push(profile)
                    }
                    //用state保存变量的当前状态
                    this.setState({
                        fieldList: userprofile
                    })
                })
                .catch(error => message.error("Network error"));
        }


    }
    //state是一个component里面的对象
    state = {
        fieldList: []
    }
    //点击登出按钮，登出完之后跳转到登录界面
    logout = () => {
        localStorage.removeItem("user")
        message.success("logout succeed")
        setTimeout(() => {
            window.location.href = "/#/login";
        }, 500);
    }

    generateName = (name) => {
        if (name == undefined) {
            return ""
        } else {
            return name.slice(0, 1).toUpperCase()
        }
    }

    render = () => {
        const colorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae'];

        return (
            <div style={{ width: '100%', justifyContent: "center" }}>
                <Row>
                    <Col span={8} style={{ dsplay: "flex", justifyContent: "center" }}>
                        <Card style={{ width: 300, height: 400, marginTop: 15, textAlign: "center", marginLeft: "80px" }}>
                            <Avatar style={{ backgroundColor: colorList[Math.floor(Math.random() * 4)], verticalAlign: 'middle' }} size={200}>
                                <div style={{ fontSize: "100px" }}>{this.generateName(this.obj.name)}</div>
                            </Avatar>
                            <div style={{ marginTop: "50px", fontWeight: "bold", fontSize: 30 }}>Welcome<div> {formatName(this.obj.name)}</div></div>
                        </Card>
                    </Col>
                    <Col span={16}>
                        <Card title="User Profile" extra={<Button type={'link'} onClick={this.logout}>Logout</Button>} style={{ width: 450, marginTop: 15 }}>
                            <Form
                                {...formItemLayout}
                                name="basic"
                                // labelCol={{ span: 8 }}
                                // wrapperCol={{ span: 16 }}
                                initialValues={{ remember: true }}
                                onFinish={this.onFinish}
                                onFinishFailed={this.onFinishFailed}
                                fields={this.state.fieldList}
                            >
                                <Form.Item
                                    label="Username"
                                    name="userId"

                                    rules={[{ required: true, message: 'Please input your username!' }]}
                                >
                                    <Input placeholder="Please input your username" disabled />
                                </Form.Item>

                                <Form.Item
                                    label="Password"
                                    name="password"
                                    rules={[{ required: true, message: 'Please input your password!' }]}
                                >
                                    <Input.Password placeholder="Please input your password" />
                                </Form.Item>

                                <Form.Item
                                    label="Address"
                                    name="address"
                                    rules={[{ required: true, message: 'Please input your Address!' }]}
                                >
                                    <Input placeholder="Please input your Address" />
                                </Form.Item>

                                <Form.Item
                                    label="Phone"
                                    name="mobile"
                                    rules={[{ required: true, message: 'Please input your phone number!' }]}
                                >
                                    <Input style={{ width: '100%' }} />
                                </Form.Item>

                                <Form.Item
                                    label="Gender"
                                    name="sex"
                                    rules={[{ required: true, message: 'Please select gender!' }]}
                                >
                                    <Select placeholder="select your gender">
                                        <Option value="male">Male</Option>
                                        <Option value="female">Female</Option>
                                        <Option value="other">Other</Option>
                                    </Select>
                                </Form.Item>

                                <Form.Item
                                    label="Email"
                                    name="email"
                                    rules={[{ required: true, message: 'Please input your Email!' }]}
                                >
                                    <Input placeholder="Please input your Email" />
                                </Form.Item>

                                <Form.Item
                                    label="Name"
                                    name="name"
                                    rules={[{ required: true, message: 'Please input your Name!' }]}
                                >
                                    <Input placeholder="Please input your Name" />
                                </Form.Item>

                                <Form.Item
                                    label="Company"
                                    name="company"
                                    rules={[{ required: true, message: 'Please input your Company!' }]}
                                >
                                    <Input placeholder="Please input your Company" />
                                </Form.Item>

                                <Form.Item {...tailFormItemLayout}>
                                    <Button type="primary" htmlType="submit">
                                        Change
                                    </Button>
                                </Form.Item>

                            </Form>
                        </Card>
                    </Col>
                </Row>
            </div>

        )
    }
}